//window.addEventListener("load", game, false);

function gui()			// GUI function
{
    
}


function game()						// Main game function
{

    function player()					// A player for Scorched Earth
    {
	var pX;
	var pY;
	var image;
	var points;
	var life;
	var sAngle;
	var pro;
	this.getPlayerPosition = getPlayerPosition;
	this.changePlayerShootingAngle = changePlayerShootingAngle;
	this.toString = toString;

	//return player position
	function getPlayerPosition()
	{
	    return [this.pX, this.pY];
	};

	// takes and integer and changes the player shooting angle
	function changePlayerShootingAngle(x)
	{
	    this.sAngle += x;
	    return this.sAngle;
	};
	

	function toString()
	{
	    return 'Player Object at '+this.pX+', '+this.pY+'.\nCurrent life: '+this.life+'.\nCurrent points: '+this.points+'.\nCurrent shooting angle: '+this.sAngle+'.';
	};

    };

    function graphic()					// Loads all the images
    {
	var images = new Array();
	var points = new Array(); //the array where X,Y coordinates are stored
	var noS = 639; //set the number of final segments
	var mD = 180; //the maximum displacement of Y coordinate
	var minY = 240; //minimum value of Y coordinate
	var maxY = 440; //maximum value of Y coordinate
	points[1] = [0, Math.random() * (maxY - minY) + minY]; //any random number between minY and maxY
	points[noS+1] = [noS+1, Math.random() * (maxY - minY) + minY]; //any random number between minY and maxY
	
	var reduction = 0.4; //the amount to which mD is reduced at each iteration (it should be between 0 and 1)


	/* Image Loading */
	loadImage(player1.image);
	loadImage(player2.image);

	function loadImage(name)
	{

	    images[name] = new Image();
	    images[name].onload = function() { 
		resourceLoaded();
	    };
	    images[name].src = "images/" + name + ".png";
	}

	var totalResources = 2;
	var numResourcesLoaded = 0;
	var fps = 30;

	function resourceLoaded()
	{

	    numResourcesLoaded += 1;
	    if(numResourcesLoaded === totalResources) {
		setInterval(redraw, 1000 / fps);
	    }
	}


	function drawTerrain()
	{
	    context.beginPath();
	    context.moveTo(0, 400);
	    context.lineTo(640,400);
	    context.strokeStyle = "#000";
	    context.stroke();
	    context.closePath();
	};


	function redraw()
	{
	    dom.width = dom.width; // clears the canvas
	    
	    /* ENVIRONMENT */
	    drawTerrain(); // call to draw terrain function
	    
	    /* PLAYER 1*/	    
	    context.beginPath();	// draw the bullet
	    context.fillStyle = "#FFFF00";
	    context.arc(pro.x, pro.y, pro.r, 0, Math.PI*2, true); 
	    context.closePath();
	    context.fill();

	    context.fillStyle = "#000000"; // black color
	    context.drawImage(images[player1.image], player1.pX, player1.pY,100,40); 	    // draw the tankSx

	    context.font = "bold 12px sans-serif"; // draw angle label
	    context.fillText(player1.sAngle, 80, 25);
	    context.font = "bold 12px sans-serif"; // draw points label
	    context.fillText(player1.life, 180, 25);
	    

	    /* PLAYER 2*/
	    context.beginPath();	//draw the bullet
	    context.fillStyle = "#FFFF00";
	    context.arc(pro2.x, pro2.y, pro2.r, 0, Math.PI*2, true); 
	    context.closePath();
	    context.fill();

	    context.fillStyle = "#000000"; // black color
	    context.drawImage(images[player2.image], player2.pX, player2.pY,100,40); 	    // draw the tankDx

	    context.font = "bold 12px sans-serif"; // draw labels
	    context.fillText(player2.sAngle, 480, 25);
	    context.font = "bold 12px sans-serif"; // draw points label
	    context.fillText(player2.life, 580, 25);


	}

    };
    
    var player1turn = true;				// Players turns
    var player2turn = false;    

    function keyboardEvents()				// Listen for keyboard events
    {
    	$(document).bind('keydown',function(evt) {
			     
			     switch(evt.keyCode){
				 
    			     case 39: // right arrow
				 
				 if (player1turn == true) {
    				     
				     console.log("RightArrow has been pressed by Player1");
    				     
				     if (player1.sAngle >= 0 && player1.sAngle < 180) {
    				
					 player1.changePlayerShootingAngle(+5);
    					 pro.a = player1.sAngle;
    				     
				     } else {
    				
					 player1.pShootinAngle = 180;
    					 pro.a = player1.sAngle;
    				     
				     }
    				     console.log(pro.a);
				 
				 } else if (player2turn == true) {
    				 
				     console.log("RightArrow has been pressed by Player2");
    				     
				     if (player2.sAngle >= 0 && player2.sAngle < 180) {
    					 player2.changePlayerShootingAngle(+5);
    					 pro.a = player2.sAngle;
    				     
				     } else {
    				
					 player2.pShootinAngle = 180;
    					 pro.a = player2.sAngle;
    				     
				     }
    				     console.log(pro2.a);
				 }
    				 break;

    			     case 37: { // left arrow
    				 
				 console.log("Left arrow has been pressed by Player1.");

    				 if (player1turn == true) {

				     if (player1.sAngle > 0 && player1.sAngle <= 180) {
    				 
					 player1.changePlayerShootingAngle(-5);
    					 pro.a = player1.sAngle;
    				 
				     } else {
    				 
					 player1.pShootinAngle = 0;
    					 pro.a = player1.sAngle;
    					 
				     }
    				 
				     console.log(pro.a);

    				 } else if (player2turn == true) {
				     
				     if (player2.sAngle > 0 && player2.sAngle <= 180) {
    				 
					 player2.changePlayerShootingAngle(-5);
    					 pro.a = player2.sAngle;
    				 
				     } else {
    				 
					 player2.pShootinAngle = 0;
    					 pro.a = player2.sAngle;
    					 
				     }
    				 }
			     }
				 break;

			     case 32: { // space bar
				 
				 console.log("Space bar has been pressed");
				 
				 if (player1turn == true) {
				 
				     console.log("Player 1 turn");
				     fire(pro,1);
				     player1turn = false;
				     player2turn = true;
				     console.log("It's player 2 turn");
				 
				 } else if (player2turn == true) {
				     
				     console.log("Player 2 turn");
				     fire(pro2,-1);
				     player2turn = false;
				     player1turn = true;
				     console.log("It's player 1 turn");
				 
				 }
				 break;
			     }}});
    };

    function bullet()		// a bullet
    {
	var x;
	var y;
	var r;
	var v;
	var a;
    };
    
    function fire(p,lr)	     // animates a bullet. lr indicates the direction of the shoot
    {
	var G = 9.8; //gravity
	var W = 0; //wind
	var t = 0;
	var v0x = p.v * Math.cos(p.a * Math.PI/180); //initial horizontal velocity
	var v0y = p.v * Math.sin(p.a * Math.PI/180); //initial vertical velocity
	var startX = p.x;
	var startY = p.y;
	var loop = setInterval(function() {
				   if ((p.y < 400) && ((p.x  < 640)&&(p.x  > 0))) {
				       p.y = Math.round(startY - ( v0y * t - (1/2 * G * Math.pow(t,2)) ));
				       p.x = Math.round(startX + (v0x * lr + W) * t);
				       t+=.1; // 100 msec (virtual time)
				       // jc(id).translateTo(p.x,p.y);
				   } else {
				       clearInterval(loop);
				       checkCollision(p,player1); // check the collision
				       console.log(p.x,p.y);
				       checkWins(); // check if sm has won
				       pro.x = 80;			// re-set the properties of the bullet
				       pro.y = 385;
				       pro.r = 5;
				       pro.v = 70;
				       pro.a = player1.sAngle;
				       pro2.x = 550;		// re-set the properties of the bullet
				       pro2.y = 385;
				       pro2.r = 5;
				       pro2.v = 70;
				       pro2.a = player2.sAngle;
				   }
			       }, 10); //10 msec

    };

    function checkCollision(tank,bullet) // Checks collision between two objects
    {
	// TODO
	var collided = false;
    };
    
    function decreasePoints() // decrease the life of object (type=player).
    {
	// check which object has been hitten
	$(document).bind('keydown',function(evt) {
			     
			     switch(evt.keyCode) {

			     case 68: { // D 
				 if (player2.life > 0){
				     player2.life--;
				     checkWins();   
				 } else {player2.life = 0;}
			     }
				 break;

			     case 65: { // A
				 if (player1.life > 0){
				     player1.life--;
				     checkWins();   
				 } else {player1.life = 0;}
			     }
				 break;

			     }
			 });
    }
    
    function checkWins()
    {
	if (player1.life == 0) {
	    alert("Sorry Player1, you're dead");
	} else if (player2.life == 0) {
	    alert("Sorry Player2, you're dead");
	}
    }
    
    /* INITIALIZE THE CANVAS */
    var dom = document.getElementById("myCanvas");
    var context = dom.getContext("2d");

    /* INITIALIZE THE GAME */
    var player1 = new player();	// create the first  player
    var pro = new bullet();	// create a bullet
    player1.pX = 50;		// set the properties of the player
    player1.pY = 360;
    player1.image = "tankSx";
    player1.points = 10;
    player1.life = 4;
    player1.sAngle = 60;
    pro.x = 80;			// set the properties of the bullet
    pro.y = 385;
    pro.r = 5;
    pro.v = 70;
    pro.a = player1.sAngle;
    console.log(player1.toString());

    var player2 = new player();	// create the second player
    var pro2 = new bullet();	// create the bullet
    player2.pX = 500;
    player2.pY = 360;
    player2.image = "tankDx";
    player2.points = 10;
    player2.life = 4;
    player2.sAngle = 60;
    pro2.x = 550;		// set the properties of the bullet
    pro2.y = 385;
    pro2.r = 5;
    pro2.v = 70;
    pro2.a = player2.sAngle;
    console.log(player2.toString());

    graphic();			// draw the graphic
    keyboardEvents();		// listen for keyboard events
    decreasePoints();

};
